package listener;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

//统计网站在线人数:统计session
public class OnlineListener implements HttpSessionListener {
    private int UserCount=0;
    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
        UserCount++;
        ServletContext servletContext = httpSessionEvent.getSession().getServletContext();//通过httpSessionEvent来获取servletContext对象
        Integer onlineCount = (Integer) servletContext.getAttribute("onlineCount");//获取servletContext中的onlineCount的值，开始是不存在的
        if (onlineCount == null) {
            onlineCount = new Integer(1);//往onlineCount里面存值1
            //无人登录时，session是null，不是0，所以赋值1
        } else {
            int count = onlineCount.intValue();
            onlineCount = new Integer(count + 1);//onlineCount的值+1
        }
        servletContext.setAttribute("onlineCount", onlineCount);//将改变的onlineCount值存入session中
        servletContext.setAttribute("UserCount", UserCount);
    }
    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        ServletContext servletContext = httpSessionEvent.getSession().getServletContext();
        Integer onlineCount = (Integer) servletContext.getAttribute("onlineCount");
        if (onlineCount == null) {
            onlineCount = new Integer(0);
        } else {
            int count = onlineCount.intValue();
            onlineCount = new Integer(count - 1);//当会话关闭时，onlineCount的值就-1
        }
        servletContext.setAttribute("onlineCount", onlineCount);
    }
}